package org.grayrabbit.cloud.core.config;

import java.io.ByteArrayInputStream;
import java.io.StringReader;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

public class StringXmlConfigurator extends Configurator {
	private String file;
	private String root;

	public StringXmlConfigurator(String xmlString) {
		this.file = xmlString;
		this.root = "string(/argument";
	}

	public StringXmlConfigurator(String xmlString, String root) {
		this.file = xmlString;
		this.root = ("string(/" + root);
	}

	private String op(String exp) throws ConfiguratorException {
		try {
			XPath path = XPathFactory.newInstance().newXPath();
			String value = (String) path.evaluate(exp, new InputSource(
					new ByteArrayInputStream(this.file.getBytes())),
					XPathConstants.STRING);
			if (StringUtils.isBlank(value))
				return null;
			return value.trim();
		} catch (XPathException e) {
			throw new ConfiguratorException(e);
		}

	}

	protected String read(String category, String name, String property)
			throws ConfiguratorException {
		String path = this.root;

		if (category != null) {
			path = this.root + "/" + category;
		}

		if (name != null)
			path = path
					+ String.format("[@name=\"%s\"]/", new Object[] { name });
		else {
			path = path + "/";
		}
		path = path + "@" + property + ")";

		return op(path);
	}

	public String getPropertiesValue(String name) throws ConfiguratorException {
		return read("properties", name, "value");
	}

	public String getCommandName() throws ConfiguratorException {
		return read(null, null, "name");
	}

	public static Properties parseProperties(String parameter) {
		Properties result = new Properties();
		try {
			DocumentBuilder builder = DocumentBuilderFactory.newInstance()
					.newDocumentBuilder();

			StringReader sd = new StringReader(parameter);
			InputSource inp = new InputSource(sd);
			Document document = builder.parse(inp);
			Element root = document.getDocumentElement();
			NodeList ndblist = root.getChildNodes();

			for (int i = 0; i < ndblist.getLength(); i++) {
				Node node = ndblist.item(i);
				String k = node.getAttributes().getNamedItem("name")
						.getNodeValue();
				String v = node.getAttributes().getNamedItem("value")
						.getNodeValue();
				result.put(k, v);
			}

		} catch (Exception localException) {
		}

		return result;
	}
}
